let express = require('express')
let bodyParser= require('body-parser')
let session = require('express-session')

let app  = express()



app.use(bodyParser.urlencoded({extended:true}))//解析form格式的请求体
app.use(bodyParser.json());//解析 json格式的请求
app.use(session({
  secret:'wl',
  resave:true,
  cookie:{
   maxAge:60*60*1000
  },
 // store: new RedisStore({url:'http://localhost:6379'}),
  saveUninitialized:true
}));
app.use(function(req,res,next){
  res.setHeader('Access-Control-Allow-Origin','http://localhost:8080')
  res.setHeader('Access-Control-Allow-Headers','Content-Type')
  res.setHeader('Access-Control-Allow-Methods','GET,POST,OPTIONS')
  // 解决cookie跨域
  res.setHeader('Access-Control-Allow-Credentials','true')
  if(req.method === 'OPTIONS'){
    res.end()
  }else{
    next()
  }
  let sliders = require('./mock/slider')

  app.get('/api/slider',function(req,res){
    res.json(
      {
        code:0,
        data:sliders
      }
    )
  })
  // 课程列表
  // /api/lessons/vue?offset=0&limit=5
  let lessons = require('./mock/lessons')
  app.get('/api/lessons/:category',function(req,res){
    // 获取分类
    let currentLessons = JSON.parse(JSON.stringify(lessons))
    let category = req.params.category
    // console.log(req)
    let offset = isNaN(req.query.offset)?0:parseInt(req.query.offset)
    let limit = isNaN(req.query.limit)?5:parseInt(req.query.limit)
    if(category && category != 'all'){
      currentLessons = currentLessons.filter(item => item.category === category)
      // 分页
    }
    let list = currentLessons.slice(offset,offset+limit)
    let hasMore = currentLessons.length > offset+limit
    res.json({
      code:0,
      data:{
        list,
        hasMore
      }
    })

  })
})

app.listen(3000)

let users = []
app.post('/api/reg',function(req,res){
  
  let user = req.body
  user.id = users.length>0?users[users.length-1].id+1:1
  users.push(user)
  res.json({
    code:0,
    data:{
      user,
      success:'注册成功'
    }
  })
})
app.post('/api/login',function(req,res){
  
  let user = users.find(item=>item.username===req.body.username && item.password===req.body.password)
  if(user){
    // 把登录成功的用户放到会话中
    req.session.user = user
    res.json({
      code:0,
      data:{
        user,
        success:'登录成功'
      }
    })
  }else{
    res.json({
      code:1,
      data:{
        success:'登录失败'
      }
    })
  }
  
  

})